#include "udp_echo_client.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <strings.h>
#include <string.h>
#include <netinet/in.h>
#include <stdio.h>
#include "socket_tool.h"
#include <arpa/inet.h>

void start_udp_echo_client()
{

    puts("启动udp echo client");

    struct sockaddr_in server_addr;
    bzero(&server_addr, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr.s_addr);
    server_addr.sin_port = htons(12346);

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    connect(sockfd, (struct sockaddr*) &server_addr, sizeof(server_addr));
    
    client_action(sockfd);
}

void client_action(int sockfd)
{
    size_t BUF_SIZE = 256;
    char buf[BUF_SIZE];
    char socket_buf[BUF_SIZE];
    bzero(buf, sizeof(buf));
    bzero(socket_buf, sizeof(socket_buf));

    for ( ; ; ) 
    {
        printf("输入消息：");
        if (fgets(buf, BUF_SIZE, stdin) == NULL) {
            puts("用户按下ctrl c，EOF，退出");
            break;
        }
        ssize_t send_bytes = sendto(sockfd, buf, strlen(buf) + 1, 0, NULL, 0);
        if (send_bytes < 0) {
            puts("发送异常");
            break;
        }
        int recv_bytes = recv(sockfd, socket_buf, BUF_SIZE, 0);
        if (recv_bytes < 0) {
            puts("读取服务器消息异常");
            break;
        }
        printf("收到服务器的消息：%s", socket_buf);
    }
}
